package com.example.flower_shop.service.usr.impl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.flower_shop.common.PageResult;
import com.example.flower_shop.entity.Article;
import com.example.flower_shop.exception.exception;
import com.example.flower_shop.mapper.ArticleMapper;
import com.example.flower_shop.service.usr.UsrArticleService;
import com.example.flower_shop.vo.article.ArticleRespVO;
import com.example.flower_shop.vo.article.UsrArtPageResp;
import com.example.flower_shop.vo.article.UsrArticlePageReq;
import jakarta.annotation.Resource;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

@Service
public class UsrArticleServiceImpl extends ServiceImpl<ArticleMapper, Article>
        implements UsrArticleService {
    @Resource
    private ArticleMapper articleMapper;

    @Override
    public ArticleRespVO getArticle(Long articleId) {
        ArticleRespVO respVO = articleMapper.getArticle(articleId);
        if (respVO == null) {
            return new ArticleRespVO();
        }
        return respVO;
    }

    @Override
    public PageResult<UsrArtPageResp> findArticlePage(UsrArticlePageReq req) {
        isValidSort(req);
        Page<UsrArtPageResp> page = new Page<>(req.getPage(), req.getSize());
        IPage<UsrArtPageResp> iPage = articleMapper.usrPageQuery(page, req);
        return PageResult.of(iPage.getTotal(), iPage.getCurrent(), iPage.getSize(), iPage.getRecords());
    }

    private void isValidSort(UsrArticlePageReq req) {
        String sortField = req.getSortField();
        if (StringUtils.isBlank(sortField)) {
            req.setSortField("create_time");
        } else if (!"create_time".equals(sortField) && !"visit".equals(sortField)) {
            throw new exception("排序字段不合法");
        }
        String sortDirection = req.getSortDirection();
        if (StringUtils.isBlank(sortDirection)) {
            req.setSortDirection("desc");
        } else if (!"desc".equals(sortDirection) && !"asc".equals(sortDirection)) {
            throw new exception("排序方向不合法");
        }
    }
}
